package com.kaidi.dibankecloud.activity;

import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

/**
 * Created by Administrator on 2017/1/6.
 */

public class BaseApplication extends Application{
    private boolean netConnected;
    private baseNetworkStateReceiver networkStateReceiver;

    @Override
    public void onCreate() {
        super.onCreate();
        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        networkStateReceiver = new baseNetworkStateReceiver();
        registerReceiver(networkStateReceiver,filter);
    }

    /**
     * 获取网络状态
     */
    public boolean isNetConnected() {
        return netConnected;
    }

    /**
     * 取消注册网络状态广播接收者
     */
    public void unregisterNetworkStateReceiver(){
        unregisterReceiver(networkStateReceiver);
    }

    /**
     * 网络状态广播接收者内部类
     */
    private class baseNetworkStateReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = cm.getActiveNetworkInfo();
            if(networkInfo == null){
                netConnected = false;
                return;
            }
            NetworkInfo.State state = networkInfo.getState();
            if(state == NetworkInfo.State.CONNECTED){
                netConnected = true;
            }else{
                netConnected = false;
            }
        }
    }
}
